<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">年份</label>
        <el-select
          v-model="query.year"
          size="small"
          class="filter-item"
          style="width: 90px"
          remote
          :remote-method="getDepartmentYears()"
          @change="crud.toQuery"
        >
          <el-option v-for="item in years" :key="item" :label="item" :value="item" />
        </el-select>
        <el-input
          v-model="query.name"
          clearable
          placeholder="输入名称搜索"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <date-range-picker v-model="query.estabDate" class="date-item" />
        <el-select
          v-model="query.type"
          clearable
          size="small"
          placeholder="类型"
          class="filter-item"
          style="width: 150px"
          @change="crud.toQuery"
        >
          <el-option v-for="item in dict.department_type" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
        <el-select
          v-model="query.isEnable"
          clearable
          size="small"
          placeholder="状态"
          class="filter-item"
          style="width: 90px"
          @change="crud.toQuery"
        >
          <el-option v-for="item in enabledTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
    </div>
    <!--表单组件-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      :title="crud.status.title"
      width="500px"
    >
      <el-form ref="form" inline :model="form" :rules="rules" size="small" label-width="80px">
        <el-form-item label="年份" prop="year">
          <el-input-number
            v-model="form.year"
            :min="1949"
            :max="2999"
            placeholder="请输入年份"
            style="width: 370px;"
            @blur="loadColleges"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" style="width: 370px;" />
        </el-form-item>
        <el-form-item label="成立日期">
          <el-date-picker v-model="form.estabDate" placeholder="请选择成立日期" type="date" style="width: 370px;" format="yyyy年MM月dd日" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="form.type" filterable placeholder="请选择" style="width: 370px;">
            <el-option v-for="item in dict.department_type" :key="item.id" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model.number="form.sort" :min="0" :max="999" controls-position="right" style="width: 370px;" />
        </el-form-item>
        <el-form-item label="顶级院系">
          <el-radio-group v-model="form.isTop" style="width: 140px">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="isEnable">
          <el-radio v-for="item in dict.data_status" :key="item.id" v-model="form.isEnable" :label="item.value">{{ item.label }}</el-radio>
        </el-form-item>
        <el-form-item v-if="form.isTop === '0'" style="margin-bottom: 0;" label="上级院系">
          <el-select
            v-model="form.parentId"
            filterable
            placeholder="请选择"
            style="width: 370px;"
          >
            <el-option
              v-for="item in colleges"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      lazy
      :load="getDepartmentDatas"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      :data="crud.data"
      row-key="id"
      @select="crud.selectChange"
      @select-all="crud.selectAllChange"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column :selectable="checkboxT" type="selection" width="50" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="year" label="年份" width="80" />
      <el-table-column prop="estabDate" label="成立日期" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.estabDate, '{y}年{m}月{d}日') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" width="80">
        <template slot-scope="scope">
          {{ dict.label.department_type[scope.row.type] }}
        </template>
      </el-table-column>
      <el-table-column prop="certifiedNum" label="已认证人数" width="100" />
      <el-table-column prop="sort" label="排序" width="50" />
      <el-table-column prop="isEnable" label="状态" fixed="right" width="50">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isEnable" active-color="#409EFF" inactive-color="#F56C6C" @change="changeEnabled(scope.row, scope.row.isEnable)" />
        </template>
      </el-table-column>
      <el-table-column
        v-permission="['admin','department:edit','department:del']"
        label="操作"
        width="150px"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <udOperation :data="scope.row" :permission="permission" :disabled-dle="scope.row.id === 1" msg="确定删除吗,如果存在下级节点则一并删除，此操作不能撤销！" />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import crudDepartment from '@/api/anniversary/department'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import CRUD, {
  presenter,
  header,
  form,
  crud
} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import DateRangePicker from '@/components/DateRangePicker'

const defaultForm = {
  id: null,
  name: null,
  isTop: '1',
  estabDate: null,
  type: null,
  parentId: null,
  certifiedNum: 0,
  sort: 1,
  remark: null,
  isEnable: true
}
export default {
  name: 'Department',
  components: {
    crudOperation,
    rrOperation,
    udOperation,
    DateRangePicker
  },
  cruds() {
    return CRUD({
      title: '院系架构',
      url: 'api/department',
      sort: 'year,desc',
      queryOnPresenterCreated: false,
      crudMethod: { ...crudDepartment
      }
    })
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  // 设置数据字典
  dicts: ['department_type', 'data_status'],
  data() {
    return {
      colleges: [],
      departments: [],
      years: [],
      loading: false,
      rules: {
        name: [{
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        }],
        sort: [{
          required: true,
          message: '请输入序号',
          trigger: 'blur',
          type: 'number'
        }]
      },
      permission: {
        add: ['admin', 'department:add'],
        edit: ['admin', 'department:edit'],
        del: ['admin', 'department:del']
      },
      enabledTypeOptions: [{
        key: 'true',
        display_name: '启用'
      },
      {
        key: 'false',
        display_name: '禁用'
      }
      ],
      queryTypeOptions: [{
        key: 'name',
        display_name: '名称'
      }]
    }
  },
  methods: {
    loadColleges(e) {
      this.colleges = []
      if (this.form.year) {
        crudDepartment.getColleges({ college: '', year: this.form.year }).then(res => {
          this.colleges = res
        })
      }
    },
    getDepartmentDatas(tree, treeNode, resolve) {
      const params = {
        parentId: tree.id
      }
      setTimeout(() => {
        crudDepartment.getDepartments(params).then(res => {
          resolve(res.content)
        })
      }, 100)
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      if (form.id != null) {
        form.year = `${form.year}`

        this.colleges = []
        if (form.year) {
          crudDepartment.getColleges({ college: '', year: this.form.year }).then(res => {
            this.colleges = res
            // form.parentId = `${form.parentId}`
            console.log(this.colleges)
          })
        }

        // this.loadColleges(null)
        // form.parentId = `${form.parentId}`
      } else {
        form.year = null
      }
      if (form.parentId !== null) {
        form.isTop = '0'
      } else if (form.id !== null) {
        form.isTop = '1'
      }
      if (form.type != null) {
        form.type = `${form.type}`
      }
      form.isEnable = `${form.isEnable}`
    },
    getDepartmentYears() {
      if (this.loading === false) {
        setTimeout(() => {
          this.loading = true
          crudDepartment.getDepartmentYears({ 'college': '' }).then(res => {
            if (res != null) {
              this.years = res
              this.query.year = res[0]
              this.crud.toQuery()
            }
          })
        }, 10)
      }
    },
    // 提交前的验证
    [CRUD.HOOK.afterValidateCU]() {
      if (this.form.parentId !== null && this.form.parentId === this.form.id) {
        this.$message({
          message: '上级院系不能为空',
          type: 'warning'
        })
        return false
      }
      if (this.form.isTop === '1') {
        this.form.parentId = null
      }
      return true
    },
    // 改变状态
    changeEnabled(data, val) {
      this.$confirm('此操作将 "' + this.dict.label.data_status[val] + '" ' + data.name + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudDepartment.edit(data).then(res => {
          this.crud.notify(this.dict.label.data_status[val] + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          data.isEnable = !data.isEnable
        })
      }).catch(() => {
        data.isEnable = !data.isEnable
      })
    },
    checkboxT(row, rowIndex) {
      return row.id !== 1
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
	/deep/ .vue-treeselect__control,
	/deep/ .vue-treeselect__placeholder,
	/deep/ .vue-treeselect__single-value {
		height: 30px;
		line-height: 30px;
	}
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
	/deep/ .el-input-number .el-input__inner {
		text-align: left;
	}
</style>
